<template>
  <div :class="[className, 'menu-list']" v-show="showMenu">
    <div v-for="item in menu" :key="item" @click="handleCilck(item.label)">
      {{ item.label }}
    </div>
  </div>
</template>

<script>
export default {
  name: "MenuList",
};
</script>

<script setup>
import { onBeforeUnmount, onMounted, ref } from "vue";

const props = defineProps(["menu", "className"]);
const emit = defineEmits(["choose"]);

const showMenu = ref(false);

const container = ref(null);

const openMenu = (e) => {
  e.preventDefault();
  e.stopPropagation();
  showMenu.value = true;
  const contextMenu = document.querySelector(`.${props.className}`);
  contextMenu.style.left = e.clientX + "px";
  contextMenu.style.top = e.clientY + "px";
};

const closeMenu = () => {
  showMenu.value = false;
};

const handleCilck = (val) => {
  emit("choose", val);
};

onMounted(() => {
  const container = document.querySelector(`.${props.className}`).parentNode;
  container.addEventListener("contextmenu", openMenu);
  window.addEventListener("click", closeMenu, true);
  window.addEventListener("contextmenu", closeMenu, true);
});

onBeforeUnmount(() => {
  const container = document.querySelector(`.${props.className}`).parentNode;
  container.removeEventListener("contextmenu", openMenu);
  window.removeEventListener("contextmenu", closeMenu);
});
</script>

<style lang='scss' scoped>
.menu-list {
  width: 100px;
  color: #fff;
  position: fixed;
  z-index: 99999999;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
  overflow: hidden;
  div {
    height: 25px;
    width: 100%;
    background: green;
    line-height: 2;
    font-size: 12px;
  }
  div:hover {
    background: red;
    cursor: pointer;
  }
}
</style>